package top.huxy.boot.util;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import top.huxy.boot.exception.ZipFailException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ZipUtils {
    public static void unZip(String source, String dist, String password) {
        unZip(new File(source), dist, password);
    }

    public static List<File> unZip(File zipFile, String dist, String password) {
        try {
            ZipFile zFile = new ZipFile(zipFile); // 首先创建ZipFile指向磁盘上的.zip文件

            zFile.setFileNameCharset("GBK");

            if (zFile.isEncrypted()) {
                if (StringUtils.isEmpty(password)) {
                    throw new ZipFailException("解压密码不能为空");
                } else {
                    zFile.setPassword(password.toCharArray()); // 设置密码
                }
            } else {
                throw new ZipFailException("安全起见,压缩文件必须设置密码");
            }

            File destDir = new File(dist);
            if (!destDir.exists()) {// 目标目录不存在时，创建该文件夹
                if (!destDir.mkdirs()) {
                    throw new ZipFailException("创建目录" + dist + "失败");
                }
            }
            zFile.extractAll(dist); // 将文件抽出到解压目录(解压)
            List<FileHeader> headerList = zFile.getFileHeaders();
            List<File> extractedFileList = new ArrayList<>();
            for (FileHeader fileHeader : headerList) {
                if (!fileHeader.isDirectory()) {
                    extractedFileList.add(new File(destDir, fileHeader.getFileName()));
                }
            }
            File[] extractedFiles = new File[extractedFileList.size()];


            extractedFileList.toArray(extractedFiles);

            return extractedFileList;

        } catch (ZipException e) {
            throw new ZipFailException("文件解压失败", e);
        }
    }
}
